<template>
  <div class="body">
    <div id="map"></div>
    <div ref="target" class="module" v-show="showModule">
      <div class="moduletitle titlecolor">EXPLORE ALL COUNTRIES</div>
      <div class="introduce">介绍介绍介绍介绍介绍介绍介绍介绍介绍介绍介绍介绍介绍</div>
      <div class="routerbox">
        <div class="button search" @click="showMarkets()">开始探索</div>
        <div class="button listshow" @click="scrollToElement()">列表查看</div>
      </div>
    </div>
  </div>
</template>

<script>
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';
import chinaGeoJson from '@/assets/json/ChinaGeoJson.json';
// import { apiGet } from '@/assets/js/api';

export default {
  name: 'MyMapComponent',
  props: {
    cmarkers: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      markers: [
        { id: 18, name: '帕劳', coords: [11, 114.561224] },
        { id: 2, name: '区域二', coords: [10.919093, 113.661224] },
        { id: 3, name: '区域三', coords: [10.519093, 112.461224] }
      ],
      chinaGeoJson,
      showModule: true,
      countryIPList: [],
      Map: null,
      mapMarkers: [] // 存储创建的标记点引用
    }
  },
  mounted() {
    // 初始化标记点
    this.markers = Object.entries(this.cmarkers).map(([key, value]) => ({
      originalKey: key,
      ...value
    }));
    console.log(this.markers);
    
    // 初始化地图
    this.Map = L.map('map', { attributionControl: false, zoomControl: false}).setView([10.819093, 113.561224], 5);

    // 添加图层
    L.tileLayer(
      'http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', 
      {
        maxZoom: 10,
        minZoom: 3,
        subdomains: '1234'
      }
    ).addTo(this.Map);

    // 添加中国地图
    const china = L.geoJSON(this.chinaGeoJson, {
      style: {
        color: 'red',
        weight: 2,
        fillOpacity: 0.1
      }
    }).addTo(this.Map);
    china.on('click', (e) => {
      console.log('点击了中国');
      e.layer.closePopup();
    })
  },
  beforeUnmount() { // 更新为Vue 3生命周期钩子
    // 组件销毁前清理地图资源
    this.cleanupMap();
  },
  methods: {
    showMarkets() {
      this.showModule = false;
      this.markers = Object.entries(this.cmarkers).map(([key, value]) => ({
        originalKey: key,
        ...value
      }));
      
      // 清理之前的标记点
      this.cleanupMapMarkers();
      
      // 设置标记点样式
      const customIcon = L.icon({
        iconUrl: require('@/assets/img/icon/marker.png'),
        iconSize: [25, 41],
        iconAnchor: [12, 41],
      });
      
      // 创建新的标记点
      this.markers.forEach(markerData => {
        const marker = L.marker(markerData.coords, { icon: customIcon }).addTo(this.Map);
        
        // 创建自定义弹出窗口内容
        const popupContent = this.createPopupContent(markerData);
        marker.bindPopup(popupContent);
        
        // 绑定点击事件
        marker.on('click', () => {
          const button = document.getElementById(`popup-button-${markerData.id}`);
          if (button) {
            button.addEventListener('click', () => {
              this.goToDetail(markerData.id);
            });
          }
        });
        
        // 存储标记点引用以便后续清理
        this.mapMarkers.push(marker);
      });
    },
    createPopupContent(markerData) {
      return `
        <div>
          <div style="font-weight: bold; color: #333; margin-bottom: 10px; font-size: 1.2em;">${markerData.name}</div>
          <button id="popup-button-${markerData.id}" style="padding: 10px 20px; background-color: #007BFF; color: white; border: none; border-radius: 5px; cursor: pointer;">国家介绍</button>
        </div>
      `;
    },
    goToDetail(id) {
      console.log(`跳转到详情，标记ID: ${id}`);
      this.$router.push({ name: 'country', query: { id: id } });
    },
    scrollToElement() {
      const element = this.$refs.target;
      const elementBottom = element.getBoundingClientRect().bottom + window.scrollY;
      const offset = window.innerHeight;
      const scrollToPosition = -elementBottom + offset;

      window.scrollTo({
          top: scrollToPosition,
          behavior: 'smooth'
      });
    },
    cleanupMapMarkers() {
      // 移除所有标记点
      this.mapMarkers.forEach(marker => {
        if (marker && this.Map && marker.remove) {
          marker.remove();
        }
      });
      this.mapMarkers = [];
    },
    cleanupMap() {
      // 清理地图资源
      this.cleanupMapMarkers();
      
      if (this.Map) {
        this.Map.off(); // 移除所有事件监听器
        this.Map.remove(); // 移除地图实例
        this.Map = null;
      }
    }
  }
};
</script>

<style scoped lang="scss">
.body{
  width: 100%;
  height: 400px;
}
#map {
  width: 100%;
  height: 400px;
  border: 1px solid black;
  margin: auto;
  background-color: pink;
}
.module{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 998;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 10px 100px;
  .moduletitle{
    font-size: 55px;
  }
  .introduce{
    margin-top: 30px;
    color: white;
  }
  .routerbox{
    display: flex;
    justify-content: space-between;
    margin-top: 100px;
    width: 230px;
    .button{
      width: fit-content;
      font-size: 13px;
      border-radius: 3px;
      font-weight: bold;
      padding: 6px 15px;
      color: white;
      cursor: pointer;
    }
    .search{
      background-color: rgb(255, 196, 0);
    }
    .listshow{
      border: 1px solid white;
    }
  }
}
</style>

 